package servlet;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import util.enviaEmail;
import bean.empresaBean;
import conexao.Conexao;
import dao.empresaDao;

public class alterarLogo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public alterarLogo() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();

		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}

		try {

			boolean podeRecuperar = ServletFileUpload
					.isMultipartContent(request);
			Integer id = (Integer) request.getSession().getAttribute(
					"idempresa");
			// se for um multipar
			if (podeRecuperar) {

				FileItemFactory fabrica = new DiskFileItemFactory();

				FileItemFactory fabItem = fabrica;
				ServletFileUpload upload = new ServletFileUpload(fabItem);

				List<?> parseRequest = upload.parseRequest(request);

				for (Object a : parseRequest) {
					FileItem Fils = (FileItem) a;
					if (!Fils.isFormField()) {
						InputStream foto = Fils.getInputStream();

						int imgLargura = 247;
						int imgAltura = 111;

						BufferedImage imagem = ImageIO.read(foto);

						Double novaImgLargura = (double) imagem.getWidth();
						Double novaImgAltura = (double) imagem.getHeight();

						Double imgProporcao = null;
						if (novaImgLargura >= imgLargura) {
							imgProporcao = (novaImgAltura / novaImgLargura);
							novaImgLargura = (double) imgLargura;
							novaImgAltura = (novaImgLargura * imgProporcao);
							while (novaImgAltura > imgAltura) {
								novaImgLargura = (double) (--imgLargura);
								novaImgAltura = (novaImgLargura * imgProporcao);
							}
						} else if (novaImgAltura >= imgAltura) {
							imgProporcao = (novaImgLargura / novaImgAltura);
							novaImgAltura = (double) imgAltura;
							while (novaImgLargura > imgLargura) {
								novaImgAltura = (double) (--imgAltura);
								novaImgLargura = (novaImgAltura * imgProporcao);
							}
						}

						BufferedImage novaImagem = new BufferedImage(novaImgLargura.intValue(),	novaImgAltura.intValue(), BufferedImage.TYPE_INT_RGB);
						Graphics g = novaImagem.getGraphics();
						g.drawImage(imagem.getScaledInstance(novaImgLargura.intValue(),	novaImgAltura.intValue(), 10000), 0, 0, null);
						g.dispose();

						ByteArrayOutputStream buffer = new ByteArrayOutputStream();

						// escreve a imagem no OutputStream
						ImageIO.write(novaImagem, "png", buffer);

						byte[] by = buffer.toByteArray();

						empresaBean empresa = new empresaBean();
						empresa.setId(id);
						empresa.setLogo(by);
						new empresaDao().alterarLogo(conn, empresa);
						conn.commit();

					}
				}
			}
			
			response.sendRedirect("empresa.jsp");

		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
				ex.printStackTrace();
			}
			new enviaEmail().enviar(e);
			throw new RuntimeException(e);
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
			}
		}

	}

}
